/**
 * 
 */
package cn.ad.server.web.spring.service.components.adtraffic2;

import cn.ad.server.common.utils.SpringContextUtils;
import cn.ad.server.web.exception.AdServerMessageException;
import cn.ad.server.web.spring.model.sts.STSAdResponse;
import cn.ad.server.web.spring.service.actions.context.AdContext;
import cn.ad.server.web.spring.service.components.adtraffic.ITrafficDispatcher;
import cn.ad.server.web.spring.service.components.adtraffic.TrafficRequest;
import cn.ad.server.web.spring.service.components.adtraffic.TrafficResponse;
import cn.ad.server.domain.ad.AdSpace;
import cn.ad.server.domain.ad.AdSpaceAdxMap;
import cn.ad.server.domain.enumration.OS;
import cn.ad.server.domain.enumration.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广点通流量分发接口实现
 * 
 * @author wangwei
 */
@Component("trafficDispatcher")
public class TrafficDispatcher implements ITrafficDispatcher {

	private static Logger logger = LoggerFactory.getLogger(TrafficDispatcher.class);

	private static Map<Integer, SSPDispatcher> dispatcherMap = new HashMap<>();

	static {
		dispatcherMap.put(3, SpringContextUtils.getBean(GDTSSPDispatcher.class));
		dispatcherMap.put(9, SpringContextUtils.getBean(JesgooSSPDispatcher.class));
		dispatcherMap.put(10, SpringContextUtils.getBean(BESSSPDispatcher.class));
	}

	@Override
	public TrafficResponse dispatch(TrafficRequest request) {

		AdContext adContext = (AdContext) request.getExParam("AdContext");
		STSAdResponse.AdSpace adSpace = (STSAdResponse.AdSpace) request.getExParam("STSAdResponse.AdSpace");
		AdSpace localAdSpace = (AdSpace) request.getExParam("AdSpace");
		ReturnCode returnCode = (ReturnCode) request.getExParam("ReturnCode");
        List<AdSpaceAdxMap> adSpaceAdxMaps = localAdSpace.getAdSpaceAdxMaps();
        STSAdResponse.AdSpace responseAdspace = null;
		if (CollectionUtils.isEmpty(adSpaceAdxMaps) || (OS.osMap.get(adContext.getOs()) == OS.ANDROID && StringUtils.isEmpty(adContext.getImeiori()))) {
			throw new AdServerMessageException(returnCode);
		} else {
			for (AdSpaceAdxMap adSpaceAdxMap : adSpaceAdxMaps) {
				//可以设置每个channel对应一种转发方式
				try {
					responseAdspace = dispatcherMap.get(adSpaceAdxMap.getChannelId()).request(adContext, adSpace, localAdSpace.getAdTemplate(), adSpaceAdxMap);
 				} catch (Exception e) {
					//TODO 广点通不返回广告时，无法序列化
					continue;
				}

				if (responseAdspace != null) {
					break;
				}
			}
		}

        if (responseAdspace == null) {
            throw new AdServerMessageException(returnCode);
        }
		TrafficResponse response = new TrafficResponse();
		response.addExParam("STSAdResponse.AdSpace", adSpace);
		return response;
	}
	
}
